/**
 * 百度地图api
 */
var map = new BMap.Map("container"); // 创建地图实例 
var point = new BMap.Point(-73.98635, 40.74852); // 创建点坐标 
//地图图标的大小
var bigIconSize = new BMap.Size(46, 50);
var bigImageSize = new BMap.Size(46, 50);

var bigIconSize2 = new BMap.Size(10, 10);
var bigImageSize2 = new BMap.Size(10, 10);

var lonStar = 1000;
var lonEnd = -1000;
var latStar = 1000;
var latEnd = -1000;

var IconStatus = 1;
var iconDy = {
  // anchor: bigIconSize,
  imageSize: bigImageSize
};
var iconDy2 = {
  // anchor: bigIconSize,
  imageSize: bigImageSize2
};
//Icon图标
var bigIconArr = [new BMap.Icon('./image/bi_0.png', bigIconSize, iconDy),
  new BMap.Icon('./image/bi_1.png', bigIconSize, iconDy),
  new BMap.Icon('./image/bi_2.png', bigIconSize, iconDy),
  new BMap.Icon('./image/bi_3.png', bigIconSize, iconDy),
];
var bigIconArr1 = [new BMap.Icon('./image/si_0.png', bigIconSize2, iconDy2),
  new BMap.Icon('./image/si_1.png', bigIconSize2, iconDy2),
  new BMap.Icon('./image/si_2.png', bigIconSize2, iconDy2),
  new BMap.Icon('./image/si_3.png', bigIconSize2, iconDy2),
];

var bigDockArr = [new BMap.Icon('./image/bd_0.png', bigIconSize, iconDy),
  new BMap.Icon('./image/bd_1.png', bigIconSize, iconDy),
  new BMap.Icon('./image/bd_2.png', bigIconSize, iconDy),
  new BMap.Icon('./image/bd_3.png', bigIconSize, iconDy),
];

var InfoOpt = {
  width: 180, // 信息窗口宽度
  height: 140, // 信息窗口高度
  offset: {
    width: 1,
    height: 1
  },
  enableAutoPan: true
};
var markMap = new Map();


var startLevel;
var endLevel;

var drag_star_lat;
var drag_end_lat;

var drag_star_lon;
var drag_end_lon;



// 开启滚轮缩放
map.enableScrollWheelZoom(true);

var opts = {
  offset: new BMap.Size(150, 5),

}
map.addControl(new BMap.ScaleControl());
map.addControl(new BMap.NavigationControl(opts));
map.centerAndZoom(point, 13); // 初始化地图，设置中心点坐标和地图级别

var marker = new BMap.Marker(point); // 创建标注    
map.addOverlay(marker);

//开始缩放
map.addEventListener("zoomstart", function () {
  let ZoomLevel = this.getZoom();
  startLevel = ZoomLevel;
});



//添加等级监视
//结束缩放
map.addEventListener("zoomend", function () {
  // alert("地图缩放至：" + this.getZoom() + "级");
  let ZoomLevel = this.getZoom();
  endLevel = ZoomLevel;
  if (ZoomLevel <= "13") {
    if (IconStatus == 0 || IconStatus == 2) {
      IconStatus = 1;
      map.clearOverlays(); //删除所有点  
      kaisi();
    }
  } else {
    if (IconStatus == 1) {
      IconStatus = 0;
      map.clearOverlays(); //删除所有点  
      kaisi();
    }
  }
  let data = {
    zoom_start_level: startLevel,
    zoom_end_level: endLevel
  };
  saveUserOpeartion(3, data);
});




//开始移动方法
map.addEventListener("movestart", function (e) {
  console.log("开始移动----")
  console.log(e);
  drag_star_lat = map.getCenter().lat;
  drag_star_lon = map.getCenter().lng;
  console.log("------------");
});
//添加拖拽监视
//结束移动方法
map.addEventListener("moveend", function (e) {
  // alert("拖拽");
  drag_end_lat = map.getCenter().lat;
  drag_end_lon = map.getCenter().lng;

  let data = {
    drag_start_lat: drag_star_lat,
    drag_start_lon: drag_star_lon,
    drag_end_lat: drag_end_lat,
    drag_end_lon: drag_end_lon
  };
  console.log("移动结束----")
  console.log(e);
  console.log(data);
  console.log("------------");

  saveUserOpeartion(1, data);
})


// 添加自定义控件
var cr = new BMap.CopyrightControl({
  anchor: BMAP_ANCHOR_TOP_RIGHT
}); //设置版权控件位置
map.addControl(cr);
var bs = map.getBounds(); //返回地图可视区域
var content = "<div>" +
  "<div style='width:200px; height:200px; display:inline;'>" +
  "<span style='width:200px; height:200px; border:1px solid #ccc; display:block';>" +
  "<a><img style='CURSOR: pointer' src='./image/bike.png'  onclick='toBike()'>" +
  "</a></span>" +
  "</div>" +
  "<div style='width:200px; height:200px; display:inline; margin-left: 10px;'>" +
  "<span style='width:200px; height:200px; border:1px solid #ccc; display:block';>" +
  "<a><img style='CURSOR: pointer' src='./image/dock.png'  onclick='toDock()'>" +
  "</a></span>" +
  "</div>" +
  "</div>";
cr.addCopyright({
  id: 1,
  content: content,
  bounds: bs
});

/**
 * 转换为Bike图层
 */
function toBike() {
  // alert("bike");
  var ZoomLevel = map.getZoom();
  if (ZoomLevel <= "13") {
    if (IconStatus == 0) {
      IconStatus = 1;
      map.clearOverlays(); //删除所有点  
      kaisi();
    }
  } else {
    if (IconStatus != 0) {
      IconStatus = 0;
      map.clearOverlays(); //删除所有点  
      kaisi();
    }
  }
}
/**
 * 转换为dock图层
 */
function toDock() {
  // alert("dock");
  var ZoomLevel = map.getZoom();
  console.log("zoomend:" + ZoomLevel);
  console.log("IconStatus:" + IconStatus);
  if (ZoomLevel <= "13") {
    if (IconStatus == 0) {
      IconStatus = 1;
      map.clearOverlays(); //删除所有点  
      kaisi();
    }
  } else {
    console.log("成功");
    console.log(IconStatus);
    if (IconStatus == 0) {
      IconStatus = 2;
      map.clearOverlays(); //删除所有点  
      kaisi();
    }
  }
}

/**
 * 点击mark显示窗口
 * @param {信息窗口html代码} content 
 * @param {mark信息} e 
 */
function openInfo(content, e, element) {
  var p = e.target;
  var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
  var infoWindow = new BMap.InfoWindow(content, InfoOpt); // 创建信息窗口对象 
  map.openInfoWindow(infoWindow, point); //开启信息窗口

  console.log("------------点击-----------------");
  console.log(e);

  let data = {
    station_id: element.station_id
  };
  saveUserOpeartion(2, data);
}
/**
 * 添加坐标点的点击事件
 * @param {*} content 
 * @param {*} marker 
 */
function addClickHandler(content, marker, element) {
  marker.addEventListener("click", function (e) {
    openInfo(content, e, element)
  });
}
// saveUserOpeartion(1);



function saveUserOpeartion(opearType, data) {
  //操作类型，1-拖拽，2-点击，3-滚轮缩放
  //当前时间
  var date = new Date();

  let dateYear = date.getFullYear(); //获取年 
  let dateMonth = date.getMonth(); //获取月  
  let dateDate = date.getDate(); //获取当日
  let dateDay = date.getDay(); //获取当日星期数
  let dateHours = date.getHours(); //获取小时
  let dateMinutes = date.getMinutes(); //获取分钟
  let dateSeconds = date.getSeconds(); //获取秒
  let dateMilliseconds = date.getMilliseconds(); //获取毫秒
  var realTime = dateYear + "-" + dateMonth + "-" + dateDate + " " + dateHours + ":" + dateMinutes + ":" + dateSeconds;
  //获取用户ip
  // var userip = returnCitySN["cip"];
  var submitInfo = {
    optType: opearType,
    userIp: '',
    createdTime: realTime,
    stationId: null,
    dragStartLat: null,
    dragStartLon: null,
    dragEndLat: null,
    dragEndLon: null,
    zoomStartLevel: null,
    zoomEndLevel: null
  };
  if (opearType == 1) {
    submitInfo.dragStartLat = data.drag_start_lat;
    submitInfo.dragEndLat = data.drag_end_lat;

    submitInfo.dragStartLon = data.drag_start_lon;
    submitInfo.dragEndLon = data.drag_end_lon;
  } else if (opearType == 2) {
    submitInfo.stationId = data.station_id;
  } else if (opearType == 3) {
    submitInfo.zoomStartLevel = data.zoom_start_level;
    submitInfo.zoomEndLevel = data.zoom_end_level;
  }

  console.log("---------------操作-------------------");
  console.log(submitInfo);
  console.log("--------------------------------------");

  //发起请求  保存用户操作数据
  $.ajax({
    // 请求方式为get或者post等
    type: "POST",
    // 服务器响应的数据类型
    dataType: "json",
    //发送的数据
    data: JSON.stringify(submitInfo),
    contentType: "application/json",
    // 请求的url(一般为后台接口)  
    url: "operation/save",
    // 请求成功后返回的数据，赋值给变量'data'  
    success: function (data) {
      console.log("成功保存~");
      console.log(data);
    },
    error: function (error) {
      console.log("出错!" + error.msg);
    }
  });


}

/**
 * 获取站点的等级
 * @param {剩余单车数} nba 
 * @param {站点总容量} cap 
 */
function getStationLevel(nba, cap) {
  if (nba < 0.3 * cap) {
    return 0;
  } else if (nba < 0.5 * cap) {
    return 1;
  } else if (nba < 0.7 * cap) {
    return 2;
  } else if (nba < 0.9 * cap) {
    return 3;
  } else {
    return 0;
  }
}
/**
 * 在地图上添加坐标点，并采用自定义坐标
 * @param {坐标点} point 
 * @param {index} index 
 * @param {坐标点的数据} element 
 */
function addMarker(point, index, element) { // 创建图标对象   
  //
  // 判断不同条件 给 不同的 图标
  var myIcon;
  let level = getStationLevel(element.num_bikes_available, element.capacity);
  if (IconStatus == 0) {
    myIcon = bigIconArr[level];
  } else if (IconStatus == 1) {
    myIcon = bigIconArr1[level];
  } else if (IconStatus == 2) {
    myIcon = bigDockArr[level];
  }
  // 创建标注对象并添加到地图   
  var marker = new BMap.Marker(point, {
    icon: myIcon
  });
  markMap.set(element.name, marker);
  // console.log(marker);
  var content = "<div class='mapbox-content'>" +
    "<div class='mapbox-content-header'>" +
    "<h1 class='mapbox-content-header-stationName'>" + element.name + "</h1>" +
    "</div>" +
    "<div class='mapbox-content-detail'>" +
    "<div class='mapbox-content-detail-bikes-available'>" +
    "<span class='mapbox-content-detail-bikes-available-val'>" + element.num_bikes_available + "</span>" +
    "<span class='mapbox-content-detail-bikes-available-lbl'>Bikes</span>" +
    "</div>" +
    "<div class='mapbox-content-detail-docks-available'>" +
    "<span class='mapbox-content-detail-docks-available-val'>" + element.num_docks_available + "</span>" +
    "<span class='mapbox-content-detail-docks-available-lbl'>Docks</span>" +
    "</div>" +
    "</div>" +
    "<div class='mapbox-content-footer'>" +
    "<span class='mapbox-content-footer-shortName'> Bike station:" + element.short_id + "</span>" +
    "</div>" +
    "</div>";


  // var content = "<div style='font-size:14px;color:#000 ;height:auto'><strong>name:</strong> <span class='font-size:20px'>" + element.name + " </span></br>" +
  //   "<strong>station_id:</strong> <span> " + element.station_id + "</span></br>" +
  //   "<strong>capacity:</strong><span> " + element.capacity + "</span></br>" +
  //   "<strong>lon:</strong> " + element.lon + "</br>" +
  //   "<strong>lat:</strong> " + element.lat + "</br>" +
  //   "<span style='font-size: 0.7875rem;'>docks:</span> <em style='color:red; font-size: 1.875rem;' >" + element.num_docks_available + "</em>" +
  //   "<span style='font-size: 0.7875rem; padding-left:20px;'>bikes:</span> <em style='color:red; font-size: 1.875rem;'>" + element.num_bikes_available + "</em></br>" +
  //   "<span>Bike station</span> <span style='color: #9f9f9f;font-size: 12px;'>" + element.short_id + "</span></br>" +
  //   "</div>";
  map.addOverlay(marker);
  //添加信息窗口 和 点击事件
  addClickHandler(content, marker, element);
}
var dataList1 = [];
var dataList2 = [];
var dataLit = [];
var mapData = new Map();
getData();
/**
 * 第二次获取数据
 */
function getDataAjAx2() {
  let info_url = "station/info";
  $.ajax({
    // 请求方式为get或者post等
    type: "GET",
    // 服务器响应的数据类型
    dataType: "json",
    // 请求的url(一般为后台接口)  
    url: info_url,
    // 请求成功后返回的数据，赋值给变量'data'  
    success: function (data) {
      // 对data进行操作 
      console.log("-------获取2------------");
      console.log(data);
      dataList1 = data.data.stations;
      dataList1.forEach(element => {
        var map1 = mapData.get(element.station_id);
        dataLit.push({
          "station_id": element.station_id,
          "name": element.name,
          "lat": element.lat,
          "lon": element.lon,
          "capacity": element.capacity,
          "num_docks_available": map1.num_docks_available,
          "num_bikes_available": map1.num_bikes_available,
          "station_status": map1.station_status,
          "short_id": element.short_name,
        });
        mapData.set(element.name, {
          "station_id": element.station_id,
          "name": element.name,
          "lat": element.lat,
          "lon": element.lon,
          "capacity": element.capacity,
          "num_docks_available": map1.num_docks_available,
          "num_bikes_available": map1.num_bikes_available,
          "station_status": map1.station_status,
          "short_id": element.short_name,
        });
        // console.log("结果-------->>>>");
        // console.log(dataLit);
      });
      kaisi();
    },
    // 请求失败异常后，返回的错误信息
    error: function (err) {
      console.log("错误");
    }
  });
}
/**
 * 获得数据
 */
function getData() {
  let status_url = "station/status";
  $.ajax({
    // 请求方式为get或者post等
    type: "GET",
    // 服务器响应的数据类型
    dataType: "json",
    // 请求的url(一般为后台接口)  
    url: status_url,
    // 请求成功后返回的数据，赋值给变量'data'  
    success: function (data2) {
      console.log("-------获取1------------");
      console.log(data2);
      dataList2 = data2.data.stations;
      dataList2.forEach(element => {
        mapData.set(element.station_id, element);
      });
      getDataAjAx2();
    },
    error: function (error) {
      console.log("出错!");
    }
  });

}
/**
 * 地图搜索功能:地点搜索
 */
function search() {
  let item_search = $('#searchId');
  console.log("=================");
  console.log(item_search.val())
  console.log("=================");

  function myFun() {
    var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
    map.centerAndZoom(pp, 18);
    map.addOverlay(new BMap.Marker(pp)); //添加标注
  }
  var local = new BMap.LocalSearch(map, {
    renderOptions: {
      map: map,
    },
    onSearchComplete: myFun
  });
  // var pStart = new BMap.Point(lonStar, latStar);
  // var pEnd = new BMap.Point(lonEnd, latEnd);
  // var bs = new BMap.Bounds(pStart, pEnd); //范围搜索
  local.search(item_search.val());
}
/**
 * 地图搜索功能:站点搜索
 */
function search_station() {
  let item_search = $('#searchId_station');
  console.log("=================");
  console.log(item_search.val())
  console.log("=================");
  //遍历 触发
  console.log(mapData);
  console.log("=================");
  var pointInfo = mapData.get(item_search.val());
  console.log(pointInfo);
  var content = "<div class='mapbox-content'>" +
    "<div class='mapbox-content-header'>" +
    "<h1 class='mapbox-content-header-stationName'>" + pointInfo.name + "</h1>" +
    "</div>" +
    "<div class='mapbox-content-detail'>" +
    "<div class='mapbox-content-detail-bikes-available'>" +
    "<span class='mapbox-content-detail-bikes-available-val'>" + pointInfo.num_bikes_available + "</span>" +
    "<span class='mapbox-content-detail-bikes-available-lbl'>Bikes</span>" +
    "</div>" +
    "<div class='mapbox-content-detail-docks-available'>" +
    "<span class='mapbox-content-detail-docks-available-val'>" + pointInfo.num_docks_available + "</span>" +
    "<span class='mapbox-content-detail-docks-available-lbl'>Docks</span>" +
    "</div>" +
    "</div>" +
    "<div class='mapbox-content-footer'>" +
    "<span class='mapbox-content-footer-shortName'> Bike station:" + pointInfo.short_id + "</span>" +
    "</div>" +
    "</div>";
  var point = new BMap.Point(pointInfo.lon, pointInfo.lat); //创建点 然后打开点
  var infoWindow = new BMap.InfoWindow(content, InfoOpt); // 创建信息窗口对象 
  map.openInfoWindow(infoWindow, point); //开启信息窗口
}


function hebin() {
  dataList1.forEach(element1 => {
    dataList2.forEach(element2 => {
      if (element1.station_id == element2.station_id) {
        dataLit.push({
          "name": element1.name,
          "lat": element1.lat,
          "lon": element1.lon,
          "capacity": element1.capacity,
          "num_docks_available": element2.num_docks_available,
          "num_bikes_available": element2.num_bikes_available,
          "station_status": element2.station_status
        });
        return;
      }
    });
  });
  kaisi();
}
/**
 * 生成所有的mark
 */
function kaisi() {
  console.log("----合并结果-----");
  console.log(dataLit);
  console.log("-----------------");
  dataLit.forEach((element, index) => {
    // console.log(element);
    var point = new BMap.Point(element.lon, element.lat);
    // 创建标注对象并添加到地图
    // var marker = new BMap.Marker(point);
    // map.addOverlay(marker);
    addMarker(point, index, element);
  });
}





// Vue.prototype.$http = axios


// var main = {
//   data() {
//     return {
//       bkdata: [],
//     }
//   },
//   created() {
//     // this.getData();
//     // this.initMap();
//   },
//   methods: {
//     initMap() {
//       this.map = new BMap.Map("container"); // 创建地图实例 
//       var point = new BMap.Point(-73.98635, 40.74852); // 创建点坐标 
//       var opts = {
//         offset: new BMap.Size(150, 5),
//       }
//       this.map.addControl(new BMap.ScaleControl(opts));
//       this.map.addControl(new BMap.NavigationControl(opts));
//       this.map.centerAndZoom(point, 13); // 初始化地图，设置中心点坐标和地图级别
//       this.map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
//       // this.map.setHeading(64.5); //设置地图旋转角度
//       // this.map.setTilt(73); //设置地图的倾斜角度
//       console.log("初始化完成");
//       console.log(this.map);
//     },
//     /**
//      * 在百度地图上添加一个点
//      * @param {经度} point 
//      * @param {纬度} index 
//      */
//     addMarker(point, index) { // 创建图标对象   
//       var myIcon = new BMap.Icon('./image/point.png', new BMap.Size(23, 25), {
//         // 指定定位位置。   
//         // 当标注显示在地图上时，其所指向的地理位置距离图标左上    
//         // 角各偏移10像素和25像素。您可以看到在本例中该位置即是   
//         // 图标中央下端的尖角位置。    
//         anchor: new BMap.Size(10, 25),
//         // 设置图片偏移。   
//         // 当您需要从一幅较大的图片中截取某部分作为标注图标时，您   
//         // 需要指定大图的偏移位置，此做法与css sprites技术类似。    
//         imageOffset: new BMap.Size(0, 0 - index * 25) // 设置图片偏移    
//       });
//       // 创建标注对象并添加到地图   
//       var marker = new BMap.Marker(point, {
//         icon: myIcon
//       });
//       console.log(marker);
//       map.addOverlay(marker);
//     },
//     /**
//      * 获得后台数据
//      */
//     async getData() {
//       console.log("获取数据");
//       let url = "https://gbfs.citibikenyc.com/gbfs/en/station_information.json";
//       const {
//         data: res
//       } = await this.$http.get(url);
//       console.log(res);
//       this.bkdata = res.data.stations;
//       console.log(this.bkdata);
//       //标注
//       this.bkdata.forEach((element, index) => {
//         var point = new BMap.Point(element.lon, element.lat);
//         // 创建标注对象并添加到地图   
//         this.addMarker(point, index);
//       });
//     }
//   },

// }
// var vm = Vue.extend(main);
// new vm().$mount('#container');